﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Jzy.BLL.DocManger;

using Jzy.Core.Common;
using Jzy.Core.Common.Web;
using Jzy.Model.DocManger;
using System.Web.UI.HtmlControls;
using Frame.Lib.Common;
using Frame.Lib.Core.Right;
using Frame.Lib.Utilities;
using Frame.Lib.Enums;
using Frame.Lib.Web;
using Frame.Lib.Core.Attach;
using Jzy.DAL;


namespace Jzy.Web.DocManager.Attach
{
    public partial class List : PageList
    {
        private DocumentBO _doc;

        private DocumentBO Doc
        {
            get
            {
                if (_doc == null)
                {
                    _doc = new DocumentBO();
                }
                return _doc;
            }
        }

        private string _dirID;

        private string DirID
        {
            get
            {
                if (_dirID == null)
                {
                    if (string.IsNullOrEmpty(Request["DirID"]))
                    {
                        _dirID = (new DirBO()).GetIDByCode(MenuCode).ToString();
                    }
                    else
                    {
                        _dirID = StrUtil.DecryptUrl(Request["DirID"]);
                    }
                }
                return _dirID;
            }
        }


        private string MenuCode
        {
            get
            {
                return Request["MenuCode"];
            }
        }



        private PagerSortSetting _setting;

        protected void Page_Load(object sender, EventArgs e)
        {
            _setting = this.Footer1.InitPager(new BindViewHandler(BindView));
            hidMyDocIDs.Value = ",";

            if (!IsPostBack)
            {

                Pager.BindDrp(drpPager);
                BindView();
                if (DirID != null)
                {
                    lblMenuName.Visible = true;
                    lblMenuName.Text = (new DirBO()).GetName(DirID) + "&nbsp;";
                }
            }
            AddAttr();
            base.InitSelectID(hidSelectIDs);
            JSUtil.SetTableHeight("list", 140);

        }


        private void AddAttr()
        {
            JSUtil.DelConfirm(btnDelete, "文件");
            btnMove.Attributes.Add("onclick", "moveDoc('../document/MoveDlg.aspx',document.getElementById('" + hidSelectIDs.ClientID + "'),document.getElementById('" + hidMyDocIDs.ClientID + "'),document.getElementById('" + btnRefresh.ClientID + "'))");


            //判断这个目录有没有增加文档的权限
            RecordRightBO right = new RecordRightBO("DocDirRight");
            List<int> lstBindIDs = right.GetBindIDs(AppSession.UserID, RecordRightName.Add, RightOwnerType.User);
            DirInfo info = (new DirBO()).GetInfo(DirID);
            if (AppSession.UserID == Constants.ADMIN_ID || AppSession.UserID == info.CreatorID || lstBindIDs.Contains(info.ID))
            {
                liAdd.Visible = true;

                string url = "Edit.aspx";
                if (DirID != null)
                {
                    url += "?DirID=" + DirID;
                }
                lnkAdd.HRef = "Edit.aspx?DirID=" + DirID;
            }
            else
            {
                liAdd.Visible = false;
            }

            //string url = "Edit.aspx";
            //if (DirID != null)
            //{
            //    url += "?DirID=" + DirID;
            //}

            //lnkAdd.HRef = "Edit.aspx?DirID=" + DirID;

            JSUtil.ClickBtn(lnkDelete, btnDelete);
            JSUtil.ClickBtn(lnkMove, btnMove);


            JSUtil.ShowForm(lnkAdd, "上传附件", null, "Edit.aspx?DirID=" + this.DirID, 360, 143);
        }

        private void BindView()
        {
            LVUtil.Init(lv, lvHeader);
            lv.ItemDataBound += new EventHandler<ListViewItemEventArgs>(lv_ItemDataBound);

            Pager.SetPageSize(_setting, drpPager);

            IEnumerable<AttachInfo> list = Doc.GetAttachList(int.Parse(DirID), AppSession.UserID);
            if (txtSearch.Text.Trim() != "")
            {
                list = list.Where(t => t.Name.Contains(txtSearch.Text.Trim()));
            }

            _setting.RecordCount = list.Count();

            list.Skip(_setting.SkipCount).Take(_setting.PageSize);

            lblStatistic.Text = "[&nbsp;共<b style='color:red;'> " + _setting.RecordCount + "</b>&nbsp;个附件&nbsp;]";

            lv.DataSource = list;
            lv.DataKeyNames = new string[] { "ID","CreatorID","BindID" };
            lv.DataBind();


        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (strSelectIDs == "")
            {
                return;
            }
            List<int> ids = StrUtil.SplitToInt(strSelectIDs);

           // List<int> ids = Doc.GetIDsByAttachIDs(lstSelectIDs);

            List<int> lstDisableDeleteIDs = new List<int>();

            if (AppSession.UserID != Constants.ADMIN_ID)
            {
                RecordRightBO right = new RecordRightBO(OTableName.DocRight);
                List<int> lstBindIDs = right.GetBindIDs(AppSession.UserID, RecordRightName.Delete, RightOwnerType.User);
                Dictionary<int, int> ditCreatorIDs = Doc.GetCreatorIDs(ids);
                for (int i = 0; i < ids.Count; i++)
                {
                    int selectID = ids[i];
                    if (ditCreatorIDs.ContainsKey(selectID))
                    {
                        if (ditCreatorIDs[selectID] == AppSession.UserID)
                        {
                            continue;
                        }
                    }
                    if (lstBindIDs.IndexOf(selectID) < 0)
                    {
                        lstDisableDeleteIDs.Add(selectID);
                        ids.RemoveAt(i);
                        i--;
                    }
                }
                if (lstDisableDeleteIDs.Count > 0)
                {
                    List<string> lstDisableDeleteNames = Doc.GetName(lstDisableDeleteIDs);
                    string strDisableDeleteNames = "“" + StrUtil.MergeToStr(lstDisableDeleteNames, "”，“") + "”";
                    string strScript = "alert('" + strDisableDeleteNames + "附件您没权限删除！');";
                    JSUtil.ExcuteJS(strScript);
                }
            }

            //要删除相关的图片和附件
            Doc.Delete(ids);
            BindView();
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            BindView();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindView();
        }

        protected void drpPager_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindView();
        }


        protected void lv_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                string strID = StrUtil.EncryptUrl(lv.DataKeys[((ListViewDataItem)e.Item).DataItemIndex]["ID"].ToString());
                HyperLink lnkDown = (HyperLink)e.Item.FindControl("lnkDown");
                HyperLink lnkName = (HyperLink)e.Item.FindControl("lnkName");
                lnkName.NavigateUrl = lnkDown.NavigateUrl = GlobalVar.WebAppPath + "Common/FileDownLoad.aspx?TableName=" + OTableName.DocAttach + "&ID=" + strID;
               

                int creatorID = (int)lv.DataKeys[((ListViewDataItem)e.Item).DataItemIndex]["CreatorID"];
                int bindID = (int)lv.DataKeys[((ListViewDataItem)e.Item).DataItemIndex]["BindID"];
                HyperLink lnkSetRight = (HyperLink)e.Item.FindControl("lnkSetRight");
                lnkSetRight.Style.Add("cursor", "pointer");
                lnkSetRight.Enabled = false;
                if (creatorID == AppSession.UserID || Constants.ADMIN_ID == AppSession.UserID)
                {
                    hidMyDocIDs.Value += bindID + ",";

                    string url = "../Document/SaveDocRight.aspx?DocID=" + this.Encrypt(bindID);
                    lnkSetRight.Enabled = true;

                    JSUtil.ShowForm(lnkSetRight, "设置权限", null, url, 300, 319);
                }

                CheckBox chkSelect = (CheckBox)e.Item.FindControl("chkSelect");
                foreach (Control ctl in e.Item.Controls)
                {
                    if (ctl is HtmlTableRow)
                    {
                        HtmlTableRow row = (HtmlTableRow)ctl;
                        row.Attributes.Add("onclick", "SelectTr('" + chkSelect.ClientID + "');");
                        if (row.Attributes["onmouseover"] == null)
                        {
                            row.Attributes.Add("onmouseover", "oldbg=this.className;this.className='trover';");
                            row.Attributes.Add("onmouseout", "this.className=oldbg;");
                        }
                    }
                }

                chkSelect.Attributes.Add("onclick", "SetSelectID('" + hidSelectIDs.ClientID + "','" + bindID + "')");
              

                //dt.Columns.Add("Index");
                //dt.Columns.Add("DownloadUrl");
                //string strUrl = GlobalVar.WebAppPath + "Common/FileDownLoad.aspx?TableName=" + (int)_tableName + "&ID=";
                //for (int i = 0; i < dt.Rows.Count; i++)
                //{
                //    DataRow dr = dt.Rows[i];
                //    dr["Index"] = i + 1;
                //    dr["DownloadUrl"] = strUrl + StrUtil.EncryptUrl(dr["ID"].ToString());
                //}

            }
        }
    }
}
